import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { PoemTag } from './entities/poem-tag.entity';
import { FindOptionsWhere, Like, Repository } from 'typeorm';
import { CreateDto } from './dto/create.dto';
import { DeleteDto } from './dto/delete.dto';
import { UpdateDto } from './dto/update.dto';
import { FindDto } from './dto/find.dto';
import { FindListDto } from './dto/find-list.dto';
import { PoemType } from '../poem-type/entities/poem-type.entity';
import {
  scrapePoemTagDesc,
  scrapePoemTagId,
} from 'src/common/utils/scrape/poem-tag';
import { createReadStream, createWriteStream } from 'fs';
import { createInterface } from 'readline';
@Injectable()
export class PoemTagService {
  @InjectRepository(PoemTag)
  private readonly poemTagRepository: Repository<PoemTag>;

  @InjectRepository(PoemType)
  private readonly poemTypeRepository: Repository<PoemType>;

  async create(createDto: CreateDto) {
    const poemType = await this.poemTypeRepository.findOne({
      where: {
        id: createDto.typeId,
      },
    });
    if (!poemType) {
      throw new BadRequestException('分类不存在');
    }
    const isExist = await this.poemTagRepository.findOne({
      where: {
        name: createDto.name,
      },
    });
    if (isExist) {
      throw new BadRequestException('分类名称已存在');
    }

    const poemTag = this.poemTagRepository.create({
      ...createDto,
      poemType,
    });
    return await this.poemTagRepository.save(poemTag);
  }

  async delete({ ids }: DeleteDto) {
    if (!ids || ids.length === 0) {
      throw new BadRequestException('参数错误');
    }
    const result = await this.poemTagRepository.delete(ids);
    if (result.affected === 0) {
      throw new BadRequestException('分类不存在');
    }
    return result;
  }

  async update(updateDto: UpdateDto) {
    const isExist = await this.poemTagRepository.findOne({
      where: {
        id: updateDto.id,
      },
    });
    if (!isExist) {
      throw new BadRequestException('分类不存在');
    }
    return await this.poemTagRepository.update(updateDto.id, updateDto);
  }

  async find({ id, name }: FindDto) {
    const where: FindOptionsWhere<PoemTag> = {};
    if (id) {
      where.id = id;
    }
    if (name) {
      where.name = Like(`%${name}%`);
    }
    return await this.poemTagRepository.find({
      where,
      relations: ['poemType', 'poems'],
    });
  }

  async list({ page, limit, name, ...restDto }: FindListDto) {
    const query: FindOptionsWhere<Omit<FindListDto, 'page' | 'limit'>> =
      restDto;
    if (name) {
      query.name = Like(`%${name}%`);
    }
    const [list, total] = await this.poemTagRepository.findAndCount({
      where: query,
      skip: (page - 1) * limit,
      take: limit,
      relations: ['poemType'],
    });
    return {
      list,
      total,
      page,
      limit,
    };
  }

  async processTags() {
    const tags: { name: string; url: string; type: string }[] =
      await scrapePoemTagId('https://aspoem.com/zh-Hans/tag');
    const filePath = 'src/scrape-data/poem-tag.txt';
    const writeStream = createWriteStream(filePath);

    for (const tag of tags) {
      try {
        // 1. 将对象写入文件
        writeStream.write(JSON.stringify(tag) + '\n');

        // 2. 处理关联逻辑
        const poemTag = await this.poemTagRepository.findOne({
          where: { name: tag.name },
        });

        const poemType = await this.poemTypeRepository.findOne({
          where: { name: tag.type },
        });
        console.log(`处理标签 ${tag.name}...`, poemTag, poemType);
        if (poemTag && poemType) {
          // 如果都存在，则建立关联
          poemTag.poemType = poemType;
          await this.poemTagRepository.save(poemTag);
        } else {
          // 如果不存在，则打印并跳过
          console.log(
            `跳过处理：tag "${tag.name}" 或 type "${tag.type}" 不存在`,
          );
        }
      } catch (error) {
        console.error(`处理标签 ${tag.name} 时出错:`, error);
      }
    }

    writeStream.end();
    console.log(`处理完成，数据已保存到 ${filePath}`);
  }

  async scrapeTagContent(filePath: string) {
    const fileStream = createReadStream(filePath);
    const rl = createInterface({
      input: fileStream,
      crlfDelay: Infinity,
    });

    for await (const line of rl) {
      try {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
        const { url } = JSON.parse(line);
        if (!url) continue;

        // 拼接完整URL并爬取数据
        const fullUrl = `https://aspoem.com/zh-Hans/${url}`;
        const { name, description } = await scrapePoemTagDesc(fullUrl);

        // 查找或创建poem-tag
        let poemTag = await this.poemTagRepository.findOne({ where: { name } });
        if (!poemTag) {
          poemTag = this.poemTagRepository.create({ name });
        }

        // 更新描述并保存
        poemTag.description = description;
        await this.poemTagRepository.save(poemTag);

        console.log(`成功处理: ${name}`);
      } catch (error) {
        console.error(`处理行数据时出错: ${line}`, error);
      }
    }

    console.log('所有数据已处理完成');
  }
}
